package cn.piesat.util.queue;

import cn.piesat.dao.PiesatRoleInfoDAO;
import cn.piesat.dao.PiesatUserLogDAO;
import cn.piesat.dto.PiesatUserLogDTO;
import cn.piesat.vo.AsyncVo;
import cn.piesat.vo.RecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;


/**
 * @author zyp
 * @date 2021/3/15
 */
@Component
public class OrderTask extends Thread {
    @Autowired
    private RequestQueue queue;
    @Autowired
    private PiesatUserLogDAO piesatUserLogDAO;
    @Autowired
    private PiesatRoleInfoDAO piesatRoleInfoDAO;

    private boolean running = true;

    @Override
    public void run() {
        while (running) {
            try {
                AsyncVo<String, Object> vo = queue.getOrderQueue().take();
                RecordVo params = vo.getParams();
                PiesatUserLogDTO piesatUserLogDTO = new PiesatUserLogDTO();
                piesatUserLogDTO.setId(params.getId());
                piesatUserLogDTO.setCreateTime(params.getStartTime());
                piesatUserLogDTO.setIp(params.getClientAddress());
                piesatUserLogDTO.setParams(params.getRequestParam());
                piesatUserLogDTO.setTime(params.getSpendTime());
                piesatUserLogDTO.setOperation(params.getOperation());
                piesatUserLogDTO.setUsername(params.getUserName());
                piesatUserLogDTO.setMethod(params.getUrl());
                piesatUserLogDTO.setRoleName(params.getRoles());
                if(params.getUrl().contains("oauth/token")){
                    List<String> roleList = piesatRoleInfoDAO.findRoleNmaeListByUserName(params.getUserName());
                    if(!roleList.isEmpty()&& roleList !=null ){
                        piesatUserLogDTO.setRoleName(roleList.toString());
                    }
                }
                piesatUserLogDTO.setLogType(params.getType());
                piesatUserLogDTO.setLocation(params.getLocatoion());
                piesatUserLogDAO.save(piesatUserLogDTO);
            } catch (InterruptedException e) {
                e.printStackTrace();
                running = false;
            }

        }
    }

    public void setRunning(boolean running) {
        this.running = running;
    }
}
